// API 配置和请求工具
const API_BASE_URL = 'https://luoerhu.thunderlz.cn/api';

// 获取存储的token
export const getToken = () => {
  return wx.getStorageSync('token');
};

// 获取refresh token
export const getRefreshToken = () => {
  return wx.getStorageSync('refreshToken');
};

// 设置token
export const setToken = (token: string, refreshToken?: string) => {
  wx.setStorageSync('token', token);
  if (refreshToken) {
    wx.setStorageSync('refreshToken', refreshToken);
  }
};

// 移除token
export const removeToken = () => {
  wx.removeStorageSync('token');
  wx.removeStorageSync('refreshToken');
};

// 通用请求函数
export const request = async (options: any): Promise<any> => {
  const { skipAuth, retry = true, ...restOptions } = options;
  
  // 添加认证头
  const headers = {
    'Content-Type': 'application/json',
    ...restOptions.headers,
  };
  
  if (!skipAuth) {
    const token = getToken();
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }
  }
  
  try {
    const res: any = await new Promise((resolve, reject) => {
      wx.request({
        url: `${API_BASE_URL}${restOptions.url}`,
        method: restOptions.method || 'GET',
        data: restOptions.data || {},
        header: headers,
        success: resolve,
        fail: reject,
      });
    });

    // 处理token过期，尝试自动刷新
    if (res.statusCode === 401 && retry && !skipAuth) {
      const refreshSuccess = await refreshToken();
      if (refreshSuccess) {
        // 重新发起请求
        return request({ ...options, retry: false });
      } else {
        // 刷新失败，跳转到登录页
        removeToken();
        wx.showToast({
          title: '登录已过期，请重新登录',
          icon: 'none',
          duration: 2000,
        });
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/login/index',
          });
        }, 2000);
        throw new Error('登录已过期');
      }
    }

    if (res.statusCode >= 200 && res.statusCode < 300) {
      return res.data;
    } else {
      throw new Error(res.data?.detail || res.data?.message || `请求失败: ${res.statusCode}`);
    }
  } catch (error: any) {
    // 网络错误处理
    if (error.errMsg && error.errMsg.includes('request:fail')) {
      wx.showToast({
        title: '网络连接失败，请检查网络',
        icon: 'none',
        duration: 2000,
      });
      throw new Error('网络连接失败');
    }
    throw error;
  }
};

// token刷新函数
const refreshToken = async (): Promise<boolean> => {
  const refreshToken = getRefreshToken();
  if (!refreshToken) {
    return false;
  }

    try {
      const res: any = await new Promise((resolve, reject) => {
        wx.request({
          url: `${API_BASE_URL}/token/refresh/`,
          method: 'POST',
          data: { refresh: refreshToken },
          header: { 'Content-Type': 'application/json' },
          success: resolve,
          fail: reject,
        });
      });

    if (res.statusCode === 200 && res.data.access) {
      setToken(res.data.access, refreshToken);
      return true;
    }
  } catch (error) {
    console.error('Token刷新失败:', error);
  }
  return false;
};

// 认证相关 API
export const authApi = {
  // 微信登录
  login: (code: string) => request({
    url: '/login/',
    method: 'POST',
    data: { code },
    skipAuth: true,
  }),
};

// 带认证的请求
export const authRequest = (options: any) => {
  return request(options);
};

// 不带认证的请求（用于公开数据）
export const publicRequest = (options: any) => {
  return request({ ...options, skipAuth: true });
};

// 旅游记录相关 API
export const travelApi = {
  // 获取旅游记录列表（公开数据，无需认证）
  getList: (params?: any) => publicRequest({ url: '/travel/', method: 'GET', data: params }),
  
  // 获取单个旅游记录（公开数据，无需认证）
  getDetail: (id: number) => publicRequest({ url: `/travel/${id}/`, method: 'GET' }),
  
  // 创建旅游记录
  create: (data: any) => authRequest({ url: '/travel/', method: 'POST', data }),
  
  // 更新旅游记录
  update: (id: number, data: any) => authRequest({ url: `/travel/${id}/`, method: 'PUT', data }),
  
  // 删除旅游记录
  delete: (id: number) => authRequest({ url: `/travel/${id}/`, method: 'DELETE' }),
  
  // 添加评论
  addComment: (recordId: number, content: string) => 
    authRequest({ url: `/travel/${recordId}/add_comment/`, method: 'POST', data: { content } }),
  
  // 点赞/取消点赞
  toggleLike: (recordId: number) => 
    authRequest({ url: `/travel/${recordId}/like/`, method: 'POST' }),
  
};

// 用户相关 API
export const userApi = {
  // 获取用户信息
  getProfile: (id: number) => authRequest({ url: `/users/${id}/`, method: 'GET' }),
  
  // 获取用户旅游记录
  getUserRecords: (userId: number) => authRequest({ url: '/travel/', method: 'GET', data: { user_id: userId } }),
};

export default {
  request,
  authRequest,
  authApi,
  travelApi,
  userApi,
  setToken,
  removeToken,
  getToken,
};
